package com.API.dal.providers;

import com.API.dal.entities.SalaryType;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Repository
@Scope(value = "request", proxyMode = ScopedProxyMode.INTERFACES)
public class SalaryProviderImp implements SalaryProvider {

    @Autowired
    SessionFactory sessionFactory;


    @Override
    @Transactional(readOnly=true,propagation=Propagation.SUPPORTS)
    public List<SalaryType> getSalaryTypes() {
        List<SalaryType> typeList;
        Session session = sessionFactory.getCurrentSession();
        Query query = session.createQuery("from SalaryType st");
        typeList = query.list();
        return typeList;
    }

    @Override
    @Transactional(readOnly=true,propagation=Propagation.SUPPORTS)
    public SalaryType getSalaryTypeByName(String salaryType_name) {
        SalaryType type;
        Session session = sessionFactory.getCurrentSession();
        Query query = session.createQuery("from SalaryType st where st.name = '" + salaryType_name + "'");
        type = (SalaryType) query.uniqueResult();
        return type;
    }

    @Override
    @Transactional(readOnly=true,propagation=Propagation.SUPPORTS)
    public SalaryType getSalaryTypeById(int id) {
        SalaryType type;
        Session session = sessionFactory.getCurrentSession();
        Query query = session.createQuery("from SalaryType st where st.id = " + id);
        type = (SalaryType) query.uniqueResult();
        return type;
    }

    @Override
    @Transactional(propagation= Propagation.REQUIRED, rollbackFor=Exception.class)
    public void addSalaryType(SalaryType salary) {
        Session session = sessionFactory.getCurrentSession();
        session.save(salary);
    }

    @Override
    @Transactional(propagation= Propagation.REQUIRED, rollbackFor=Exception.class)
    public void updateSalaryType(SalaryType salary) {
        Session session = sessionFactory.getCurrentSession();
        session.update(salary);
    }
}
